package com.fangngng.pushall.security;

import com.fangngng.pushall.entity.Role;
import com.fangngng.pushall.entity.User;
import com.fangngng.pushall.mapper.RoleMapper;
import com.fangngng.pushall.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author fei.fang
 * @date 2021/4/2
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * Locates the user based on the username. In the actual implementation, the search
     * may possibly be case sensitive, or case insensitive depending on how the
     * implementation instance is configured. In this case, the <code>UserDetails</code>
     * object that comes back may have a username that is of a different case than what
     * was actually requested..
     *
     * @param username the username identifying the user whose data is required.
     * @return a fully populated user record (never <code>null</code>)
     * @throws UsernameNotFoundException if the user could not be found or the user has no
     *                                   GrantedAuthority
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
        User user = new User();
        user.setEmail(username);
        user.setLifecycle(User.LIFECYCLE_ENABLE);
        List<User> userDbs = userMapper.select(user);
        User userDb = null;
        if (null != userDbs && !userDbs.isEmpty() ){
            userDb = userDbs.get(0);
            List<Role> roles = roleMapper.getRolesByUserId(userDb.getId());
            userDb.setAuthorities(roles);
        }
        return userDb;
    }
}
